import { useEffect, useState } from 'react';
import { Tooltip } from 'antd';
import styled from 'styled-components';
import ActionUtil from '@/utils/action.js';
import ModalUtil from '@/utils/modal.js';

const Copy = styled.span`
  cursor: pointer;

  &:hover {
    color: var(--ant-color-primary);
  }
`;

/**
 * JSON预览组件
 *
 * @param {object} props 属性
 * @param {object} props.json JSON对象
 */
export default function JsonView(props) {
  const [json, setJson] = useState({});

  useEffect(() => {
    if (typeof props.json === 'object') {
      setJson(props.json);
    }
  }, [props.json]);

  function copy(text) {
    ActionUtil.copyToClipboard(text, () => {
      ModalUtil.success('复制成功');
    });
  }

  return (
    <div>
      {Object.keys(json).map((key) => (
        <div key={key}>
          <Tooltip title={`复制 ${key}`}>
            <Copy onClick={() => copy(key)}>{key}</Copy>
          </Tooltip>
          :&nbsp;
          <Tooltip title={`复制 ${json[key]}`}>
            <Copy onClick={() => copy(json[key])}>{json[key]}</Copy>
          </Tooltip>
        </div>
      ))}
    </div>
  );
}
